<template>
  <ContainerContent
    :loading="loading"
    :pagination="pagination"
    @run="run"
    inner>
    <template #header>
      <a-button type="primary" @click="visible = true">
        <i-icons-btn-add />
        创建规则
      </a-button>
      <a-range-picker
        v-model="dateTimeRange"
        value-format="timestamp"
        class="!min-w-360px"
        :placeholder="['选择创建开始时间', '选择创建结束时间']"
        @change="handleDateChange"
        @clear="run" />
      <CloudFilterBar v-model="params" :run="run" :schemes="filterSchemes" />
    </template>
    <a-table
      ref="tableRef"
      v-bind="commonTableProps"
      :columns="columns"
      :data="data"
      row-key="id"
      @sorter-change="onSorterChange">
      <template #sort>
        <i-icons-draggable class="drag-icon" />
      </template>
      <template #condition_description="{ record }">
        {{ record.condition_description }}
      </template>
      <template #status="{ record }">
        <a-switch
          :model-value="record.status"
          :checked-value="1"
          :unchecked-value="2"
          size="small"
          :before-change="
            (val: number) => handleBeforeChange(val, record)
          "></a-switch>
      </template>
      <template #action="{ record }">
        <a-link :hoverable="false" @click="open(record)"> 编辑 </a-link>
        <a-link status="danger" :hoverable="false" @click="handDelete(record)">
          删除
        </a-link>
      </template>
    </a-table>
    <add-rule-dialog
      v-if="type === A_RULE_TYPE.REWRITE_URL"
      v-model:visible="visible"
      :record="ruleData"
      :type="type"
      :id="id"
      @refresh="run" />
    <add-regulation
      v-else
      v-model:visible="visible"
      :record="ruleData"
      :id="id"
      :type="type"
      @refresh="run" />
  </ContainerContent>
</template>
<script lang="ts" setup>
import type { UrlListItem } from '@/apis/model/transform'
import {
  deleteApiSiteConversionRuleApi,
  getApiSiteConversionRuleQueryApi,
  updateApiSiteConversionRulePriorityApi,
  updateApiSiteConversionRuleStatusApi
} from '@/apis/modules/site/transform'
import ContainerContent from '@/components/ContentContainer.vue'
import type { CloudFilterBarState } from '@/components/filter-bar/types'
import { A_RULE_TYPE } from '@/constants/site'
import { commonTableProps } from '@/utils/table'
import AddRegulation from './AddRegulation.vue'
import AddRuleDialog from './AddRuleDialog.vue'
import useTableColumn from './column'
import Sortable from 'sortablejs'
interface IProps {
  type: number
}
const props = withDefaults(defineProps<IProps>(), {
  type: 3
})
const dateTimeRange = ref<Date[]>([])
const route = useRoute()
const id = computed(() => route.params.id as string)
const params = ref<CloudFilterBarState>({
  order: 'asc',
  sort: 'priority',
  type: props.type,
  created_at_end: null,
  created_at_start: null,
  site_id: id.value
})
const tableRef = ref()
const { visible, open, data: ruleData } = usePopup()
const { columns, filterSchemes } = useTableColumn()
const { data, loading, run, pagination } = useListRequest(
  getApiSiteConversionRuleQueryApi,
  { params, immediate: true }
)
const { createSortChange } = useTable(run, data)
const onSorterChange = createSortChange(params)

const handleBeforeChange = (status: number, row: UrlListItem) => {
  return new Promise((resolve, reject) => {
    updateApiSiteConversionRuleStatusApi({
      id: row.id,
      status
    } as any)
      .then(() => {
        row.status = row.status === 1 ? 2 : 1
        resolve(void 0)
      })
      .finally(() => reject(false))
    // if (status === 1) {
    //   CloudModal.confirm(
    //     {
    //       content: '确定要开启此规则吗？'
    //     },
    //     async () => {
    //       await updateApiSiteConversionRuleStatusApi({
    //         id: row.id,
    //         status
    //       } as any)
    //       ToastUtils.success('操作成功')
    //       run()
    //       resolve(void 0)
    //     },
    //     () => {
    //       resolve(void 0)
    //     }
    //   )
    // } else {
    //   CloudModal.error(
    //     {
    //       content: '确定要关闭此规则吗？'
    //     },
    //     async () => {
    //       await updateApiSiteConversionRuleStatusApi({
    //         id: row.id,
    //         status
    //       } as any)
    //       ToastUtils.success('操作成功')
    //       run()
    //       resolve(void 0)
    //     },
    //     () => {
    //       resolve(void 0)
    //     }
    //   )
    // }
  })
}
const handleDateChange = (val: number[]) => {
  if (val && val.length > 0) {
    params.value.created_at_start = val[0] / 1000
    params.value.created_at_end = val[1] / 1000 + 86399
  } else {
    params.value.created_at_start = undefined
    params.value.created_at_end = undefined
  }
  run()
}
const handDelete = (row: any) => {
  CloudModal.error(
    {
      content: `确认删除规则 “${row?.name}” ？`,
      okText: '删除'
    },
    async () => {
      await deleteApiSiteConversionRuleApi({
        id: row?.id
      })
      ToastUtils.success('操作成功')
      run()
    }
  )
}
watchEffect(() => {
  run({ site_id: id.value })
})
const changeRule = async (id: string, priority: number) => {
  await updateApiSiteConversionRulePriorityApi({ id, priority })
  ToastUtils.success('操作成功')
  run()
}
onMounted(async () => {
  await nextTick()
  const el = (tableRef.value.$el as HTMLElement).querySelector('tbody')
  Sortable.create(el, {
    animation: 300,
    //设置指定列作为拖拽
    handle: '.drag-icon',
    forceFallBack: true,
    onEnd(evt: { newIndex: number; oldIndex: number }) {
      const { newIndex, oldIndex } = evt
      if (newIndex === oldIndex) {
        return
      }
      const id = data.value[oldIndex].id!
      const priority = data.value[newIndex].priority!
      changeRule(id, priority)
    }
  })
})
</script>

<style lang="less" scoped></style>
